package com.yc.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.edu.pojo.Result;
import com.yc.edu.pojo.UserVO;
import com.yc.edu.utils.JwtUtils;
import com.yc.edu.vo.*;
import com.yc.edu.dao.UserDAO;
import com.yc.edu.pojo.User;
import com.yc.edu.service.UserService;
import com.yc.edu.utils.MD5Util;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDAO, User> implements UserService {
    @Resource
    private MD5Util md5Util;
    @Resource
    private UserDAO userDAO;

    /**
     * 用户名 + 密码登录
     */

    @Override
    public Result loginByUsername(UserVO loginUserNameVO) {
        loginUserNameVO.setPassword(md5Util.getMD5(loginUserNameVO.getPassword()));
        UserVO user =userDAO.loginByMd5(loginUserNameVO);
        if (user != null) {
            log.info("登录用户成功");
            List<String> list = new ArrayList<>();
            list.add(user.getUsername());
            list.add(String.valueOf(user.getStatus()));
            // 删除以username开头的所有键
            return Result.success(list);
        }
        log.info("登录失败");
        return Result.error("账号或密码错误");
    }

    @Override
    public Result updateAvatar(String userId, String url) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("id", userId);
        User user = this.getOne(wrapper);
        user.setAvatar(url);
        return this.updateById(user) ? Result.success("个人信息更新成功") : Result.error("个人信息更新失败");
    }

    @Override
    public Result searchUser(String username) {
        UserOnLine onlineUser = userDAO.getOnlineUser(username);
        if (onlineUser == null) return Result.error("未找到该用户");
        return Result.success(onlineUser);
    }

    @Override
    public void register(UserVO user) {
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setPassword(md5Util.getMD5(user.getPassword()));
        System.out.println(user);
        userDAO.registerCommonUser(user);
    }


}
